package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chuanglan.SMSConst;
import com.chuanglan.sms.util.ChuangLanSmsUtil;
import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.common.support.Convert;
import com.ruoyi.common.utils.Constans;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.CodeRecord;
import com.ruoyi.system.domain.DepositLog;
import com.ruoyi.system.domain.HatchetAgent;
import com.ruoyi.system.domain.HatchetMerchant;
import com.ruoyi.system.domain.HatchetMoneyChange;
import com.ruoyi.system.domain.HatchetOrderPayment;
import com.ruoyi.system.domain.HatchetSystemConfig;
import com.ruoyi.system.domain.OptLog;
import com.ruoyi.system.domain.SysRole;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.mapper.HatchetMerchantMapper;
import com.ruoyi.system.service.ICodeRecordService;
import com.ruoyi.system.service.IDepositLogService;
import com.ruoyi.system.service.IHatchetAcqService;
import com.ruoyi.system.service.IHatchetAgentService;
import com.ruoyi.system.service.IHatchetCardBinService;
import com.ruoyi.system.service.IHatchetCardTypeService;
import com.ruoyi.system.service.IHatchetIssBankService;
import com.ruoyi.system.service.IHatchetMerchantService;
import com.ruoyi.system.service.IHatchetMoneyChangeService;
import com.ruoyi.system.service.IHatchetOrderPaymentService;
import com.ruoyi.system.service.IHatchetSystemConfigService;
import com.ruoyi.system.service.IOptLogService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.vo.AgentMerchantChangeVo;
import com.ruoyi.system.vo.SecurityUtils;

/**
 * 商户列 服务层实现
 * 
 * @author ruoyi
 * @date 2019-02-18
 */
@Service
public class HatchetMerchantServiceImpl implements IHatchetMerchantService {
	@Autowired
	private HatchetMerchantMapper hatchetMerchantMapper;
	@Autowired
	IHatchetSystemConfigService hatchetSystemConfigService;
	@Autowired
	IHatchetAgentService agentService;
	@Autowired
	IHatchetAcqService acqService;
	@Autowired
	IHatchetOrderPaymentService orderPaymentService;
	@Autowired
	IHatchetCardBinService cardBinService;
	@Autowired
	IHatchetCardTypeService cardTypeService;
	@Autowired
	IHatchetIssBankService issBankService;
	@Autowired
	IHatchetSystemConfigService systemConfigService;
	@Autowired
	ICodeRecordService codeRecordService;
	@Autowired
	IHatchetMoneyChangeService moneyChangeService;
	@Autowired
	ISysUserService sysUserService;
	@Autowired
	ISysRoleService sysRoleService;
	@Autowired
	IDepositLogService depositLogService;
	@Autowired
	private IOptLogService optLogService;
	/**
	 * 查询商户列信息
	 * 
	 * @param iD
	 *            商户列ID
	 * @return 商户列信息
	 */
	@Override
	public HatchetMerchant selectHatchetMerchantById(String iD) {
		return hatchetMerchantMapper.selectHatchetMerchantById(iD);
	}
	
	/**
	 * 查询商户列信息
	 * 
	 * @param phone
	 *            商户列电话
	 * @return 商户列信息
	 */
	@Override
	public HatchetMerchant selectHatchetMerchantByPhone(String phone) {
		HatchetMerchant merchant = new HatchetMerchant();
		merchant.setPHONE(phone);
		List<HatchetMerchant> selectHatchetMerchantList = selectHatchetMerchantList(merchant);
		if (StringUtils.isNotEmpty(selectHatchetMerchantList)) {
			return selectHatchetMerchantList.get(0);
		} else {
			return null;
		}
	}
	
	/**
	 * 查询商户列信息
	 * 
	 * @param merchantNo
	 *            商户编号
	 * @return 商户列信息
	 */
	@Override
	public HatchetMerchant selectHatchetMerchantByMerchantNo(String merchantNo) {
		HatchetMerchant merchant = new HatchetMerchant();
		merchant.setMerchantNo(merchantNo);
		List<HatchetMerchant> selectHatchetMerchantList = selectHatchetMerchantList(merchant);
		if (StringUtils.isNotEmpty(selectHatchetMerchantList)) {
			return selectHatchetMerchantList.get(0);
		} else {
			return null;
		}
	}

	/**
	 * 查询商户列列表
	 * 
	 * @param hatchetMerchant
	 *            商户列信息
	 * @return 商户列集合
	 */
	@Override
	public List<HatchetMerchant> selectHatchetMerchantList(HatchetMerchant hatchetMerchant) {
		return hatchetMerchantMapper.selectHatchetMerchantList(hatchetMerchant);
	}

	/**
	 * 新增商户列
	 * 
	 * @param hatchetMerchant
	 *            商户列信息
	 * @return 结果
	 */
	@Override
	public int insertHatchetMerchant(HatchetMerchant hatchetMerchant) {
		return hatchetMerchantMapper.insertHatchetMerchant(hatchetMerchant);
	}

	/**
	 * 修改商户列
	 * 
	 * @param hatchetMerchant
	 *            商户列信息
	 * @return 结果
	 */
	@Override
	public int updateHatchetMerchant(HatchetMerchant hatchetMerchant) {
		return hatchetMerchantMapper.updateHatchetMerchant(hatchetMerchant);
	}

	/**
	 * 删除商户列对象
	 * 
	 * @param ids
	 *            需要删除的数据ID
	 * @return 结果
	 */
	@Override
	public int deleteHatchetMerchantByIds(String ids) {
		return hatchetMerchantMapper.deleteHatchetMerchantByIds(Convert.toStrArray(ids));
	}

	@Override
	public HatchetMerchant selectHatchetMerchantByNo(String merchantNo) {
		return hatchetMerchantMapper.selectHatchetMerchantByNo(merchantNo);
	}

	/**
	 * 代理商查询所有商户
	 * 
	 * @param hatchetMerchant
	 * @return
	 */
	public List<HatchetMerchant> selectHatchetMerchantForDLS(HatchetMerchant hatchetMerchant) {
		return hatchetMerchantMapper.selectHatchetMerchantForDLS(hatchetMerchant);
	}

	/**
	 * 递归查询上级经纪人
	 */
	public HatchetMerchant getMerchantByPhoneOrLinkPhone(String phone) {
		List<HatchetMerchant> list = hatchetMerchantMapper.selectMerByPhone(phone);
		if (CollectionUtils.isNotEmpty(list))
			return (HatchetMerchant) list.get(0);
		else
			return null;
	}

	/**
	 * 代理商查询下属商户数量
	 * 
	 * @param departmentCode
	 * @return
	 */
	public Long selectHatchetMerchantCountForDLS(HatchetMerchant hatchetMerchant) {
		return hatchetMerchantMapper.selectHatchetMerchantCountForDLS(hatchetMerchant);
	};

	/**
	 * 代理商查询下属激活商户数量
	 * 
	 * @param departmentCode
	 * @return
	 */
	public Long selectActivHatchetMerchantCountForDLS(HatchetMerchant hatchetMerchant) {
		return hatchetMerchantMapper.selectActivHatchetMerchantCountForDLS(hatchetMerchant);
	}

	/**
	 * 通过联系
	 */
	public HatchetMerchant getMerchantByPhoneOrLinkPhone(String phone, String product) {
		List<HatchetMerchant> list = new ArrayList<>();
		HatchetMerchant merchant = new HatchetMerchant();
		merchant.setPHONE(phone);
		merchant.setProductShort(product);
		list = hatchetMerchantMapper.selectHatchetMerchantList(merchant);
		if (CollectionUtils.isNotEmpty(list))
			return (HatchetMerchant) list.get(0);

		HatchetMerchant merchant1 = new HatchetMerchant();
		merchant1.setLinkPhone(phone);
		merchant1.setProductShort(product);
		list = hatchetMerchantMapper.selectHatchetMerchantList(merchant1);
		if (CollectionUtils.isNotEmpty(list))
			return (HatchetMerchant) list.get(0);
		else
			return null;
	}

	/**
	 * 代理商查询下属商户 返回商户财务列表
	 * 
	 * @param agentId
	 * @return
	 */
	public List<AgentMerchantChangeVo> selectUnderMoneyForDLS(HatchetMerchant hatchetMerchant) {
		return hatchetMerchantMapper.selectUnderMoneyForDLS(hatchetMerchant);
	};

	/**
	 * 代理商把客户升级为经纪人的操作
	 * 
	 * @param hatchetMerchant
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public Map<String, Object> doLiftMerchant(HatchetMerchant hatchetMerchant,Integer codeCount) throws Exception {
		Map<String, Object> map = new HashMap<>();
		HatchetMerchant liftMerchant = selectHatchetMerchantById(hatchetMerchant.getID());
		// 设置经纪人的agentIda为当前代理商Id
		if ("3".equals(liftMerchant.getLEVEL())) {
			map.put("status", BusinessStatus.FAIL);
			map.put("msg", "该用户已经是经纪人无需升级");
			return map;
		}
		HatchetAgent agent = agentService.selectHatchetAgentById(hatchetMerchant.getAgentId());
		// 从配置表中获取升级经纪人所需升级码数量
		/*Integer codeCount = getUpgradeCodeCountForJJR();*/
		// 判断代理商的剩余升级码数量是否足够
		if (agent.getFastCount() < codeCount) {
			map.put("status", BusinessStatus.FAIL);
			map.put("msg", "您的剩余升级码不足,请联系您的上级");
			return map;
		}
		// 减去代理商的fastCount
		Integer subCount = agent.getFastCount() - codeCount;
		agent.setFastCount(subCount);
		int updateAgent = agentService.updateHatchetAgent(agent);
		if (updateAgent > 0) {
			// 修改商户级别和升级码数量
			hatchetMerchant.setLEVEL("3");
			hatchetMerchant.setUpgradeCodeNum("" + codeCount);
			// 更新商户升级经纪人时间
			hatchetMerchant.setSubmitReexamineTime(new Date());
			if (StringUtils.isNull(liftMerchant.getSubmitExamineTime())) {
				//升级黄金时间
				hatchetMerchant.setSubmitExamineTime(new Date());
			}
			
			
			int updateMerchant = updateHatchetMerchant(hatchetMerchant);
			if (updateMerchant < 1) {
				throw new RuntimeException("操作失败");
			} else {
				boolean creatCodeRecord = creatCodeRecord(liftMerchant, agent, codeCount);
				if (!creatCodeRecord) {
					throw new RuntimeException("升级码记录添加失败");
				}
				map.put("fastCount", subCount);// 代理商的剩余升级码数量
				map.put("level", "3");
				map.put("upgradeCodeNum", codeCount);// 商户升级后的升级码数量
				map.put("status", BusinessStatus.SUCCESS);
	            map.put("msg", "升级成功");
				return map;
			}
		} else {
			map.put("status", BusinessStatus.FAIL);
			map.put("msg", "操作失败");
			return map;
		}
	}

	/**
	 * 从配置表获取升级经纪人所需的升级码数量
	 * 
	 * @return
	 */
	public Integer getUpgradeCodeCountForJJR() {
		// 从配置表中获取升级经纪人所需升级码数量
		HatchetSystemConfig systemConfig = new HatchetSystemConfig();
		systemConfig.setConfigCode("2000024");
		List<HatchetSystemConfig> systemConfigList = hatchetSystemConfigService
				.selectHatchetSystemConfigList(systemConfig);
		// configValue 形式25:500:1000
		String configValue = systemConfigList.get(0).getConfigValue();
		// 第一个冒号前面的值就是需要升级码数量
		String[] split = configValue.split(":");
		Integer codeCount = Integer.parseInt(split[0]);
		return codeCount;
	}

	/**
	 * 每月一号定时清理经纪人月贡献
	 */
	public void cleanMerMonMoney(String defaultVule) {
		hatchetMerchantMapper.cleanMerMonMoney(defaultVule);

	}

	/**
	 * 给经纪人按照收益排序
	 * 
	 * @param hatchetMerchant
	 * @return
	 */
	public List<HatchetMerchant> sortJJR(HatchetMerchant hatchetMerchant) {
		Map<String, Object> params = hatchetMerchant.getParams();
		hatchetMerchant.setLEVEL("3");// 查询经纪人
		hatchetMerchant.setParams(null);
		List<HatchetMerchant> merchantList = selectHatchetMerchantForDLS(hatchetMerchant);
		// 查询每个经纪人的收益
		for (HatchetMerchant hatchetMerchant2 : merchantList) {
			HatchetMoneyChange moneyChange = new HatchetMoneyChange();
			moneyChange.setParams(params);
			moneyChange.setUserId(hatchetMerchant2.getMerchantNo());
			BigDecimal selectSumMoney = null;
			if ("SJ".equals(hatchetMerchant.getMoneyType())) {
				moneyChange.setMoneyType("10C");
				selectSumMoney = moneyChangeService.selectSumMoney(moneyChange);
			} else if ("FR".equals(hatchetMerchant.getMoneyType())) {
				//单独查询非升级分润
				selectSumMoney = moneyChangeService.selectSumMoneyByMoneyType(moneyChange);
			} else {
				//默认全部查询
				selectSumMoney = moneyChangeService.selectSumMoney(moneyChange);
			}
			if (StringUtils.isNull(selectSumMoney)) {
				selectSumMoney = new BigDecimal("0");
			}
			// 经纪人收益
			hatchetMerchant2.setSumMoney(selectSumMoney);
			//手机号加码
//			hatchetMerchant2.setPHONE(StringUtils.idCardNoString(hatchetMerchant2.getPHONE(),3));
		}
		// 按照总收益倒序排序
		Collections.sort(merchantList);
		// 截取前50位
		if (merchantList.size() > 50) {
			merchantList = merchantList.subList(0, 50);
		}
		return merchantList;
	}

	/**
	 * 修改用户
	 */
	@Transactional
	public Map<String, Object> editSave(HatchetMerchant hatchetMerchant) {
		Map<String, Object> map = new HashMap<>();
		HatchetMerchant merchant = selectHatchetMerchantById(hatchetMerchant.getID());
		Integer codeCount = null;
		if (StringUtils.isNotNull(merchant)) {
			// 如果当前用户为经纪人 不允许修改其等级和升级码数量
			if ("3".equals(merchant.getLEVEL())) {
				hatchetMerchant.setUpgradeCodeNum(null);
				hatchetMerchant.setLEVEL(null);
				//经理 不能升级
			}else {
				// 把普通黄金会员升级成经纪人
				if ("3".equals(hatchetMerchant.getLEVEL())) {
					// 查询升级人所需升级码数量
					codeCount = getUpgradeCodeCountForJJR();
					hatchetMerchant.setUpgradeCodeNum(codeCount + "");
					hatchetMerchant.setSubmitReexamineTime(new Date());// 升级经纪人时间
					if (StringUtils.isNull(merchant.getSubmitExamineTime())) {
						hatchetMerchant.setSubmitExamineTime(new Date());//升级黄金会员时间	
					}
				}
				// 把普通用户升级成黄金会员
				if ("2".equals(hatchetMerchant.getLEVEL())) {
					// 查询升级人所需升级码数量
					hatchetMerchant.setSubmitExamineTime(new Date());//升级黄金会员时间
				}
				//升级经理
				if ("4".equals(hatchetMerchant.getLEVEL())) {
					hatchetMerchant.setLEVEL("2");
					hatchetMerchant.setSubmitExamineTime(new Date());
					hatchetMerchant.setSubmitReexamineTime(new Date());// 升级经纪人时间
				}
			}
		} else {
			map.put("status", BusinessStatus.FAIL);
			map.put("msg", "商户不存在！");
			return map;
		}
		// 修改商户的代理商
		if (hatchetMerchant.getAgentNo() != null) {
			HatchetAgent agent = agentService.selectHatchetAgentByNo(hatchetMerchant.getAgentNo());
			if (agent != null) {
				hatchetMerchant.setAgentId(agent.getID());
				hatchetMerchant.setDepartmentCode(agent.getDepartmentCode());
				// 如果升级经纪人需要扣码
				if ("3".equals(hatchetMerchant.getLEVEL())) {
					if (agent.getFastCount() >= codeCount) {
						agent.setFastCount(agent.getFastCount() - codeCount);
						int updateHatchetAgent = agentService.updateHatchetAgent(agent);
						if (updateHatchetAgent > 0) {
							creatCodeRecord(merchant, agent, codeCount);
						} else {
							map.put("status", BusinessStatus.FAIL);
							map.put("msg", "代理商扣码失败！");
							return map;
						}
					} else {
						map.put("status", BusinessStatus.FAIL);
						map.put("msg", "代理商码不够，无法升级！");
						return map;
					}
				}
				// 如果升级黄金会员需要扣1个码
				if ("2".equals(hatchetMerchant.getLEVEL())) {
					if (agent.getFastCount() >= 1) {
						agent.setFastCount(agent.getFastCount() - 1);
						int updateHatchetAgent = agentService.updateHatchetAgent(agent);
						if (updateHatchetAgent > 0) {
							creatCodeRecord(merchant, agent, 1);
						} else {
							map.put("status", BusinessStatus.FAIL);
							map.put("msg", "代理商扣码失败！");
							return map;
						}
					} else {
						map.put("status", BusinessStatus.FAIL);
						map.put("msg", "代理商码不够，无法升级！");
						return map;
					}
				}
			} else {
				map.put("status", BusinessStatus.FAIL);
				map.put("msg", "代理商不存在！");
				return map;
			}
		}
		int updateHatchetMerchant = updateHatchetMerchant(hatchetMerchant);
		if (updateHatchetMerchant < 1) {
			throw new RuntimeException("用户修改失败");
		} else {
			map.put("status", BusinessStatus.SUCCESS);
			map.put("msg", "用户修改成功！");
			return map;
		}

	}

	/**
	 * 创建加码减码记录
	 * 
	 * @param hatchetMerchant
	 * @param agent
	 * @param codeCount
	 * @return
	 */
	@Transactional
	public boolean creatCodeRecord(HatchetMerchant hatchetMerchant, HatchetAgent agent, int codeCount) {
		// 添加加码和减码记录
		String fromId = StringUtils.randomUUID();
		String toId = StringUtils.randomUUID();
		// 创建升级码加码记录
		CodeRecord codeRecord1 = new CodeRecord();
		codeRecord1.setId(toId);
		codeRecord1.setMerchantId(hatchetMerchant.getID());
		codeRecord1.setName(hatchetMerchant.getMerchantCnName());
		codeRecord1.setCount(codeCount);
		codeRecord1.setType("0");
		codeRecord1.setField1(Integer.parseInt(hatchetMerchant.getUpgradeCodeNum())+"");
		//操作后升级码数量
		codeRecord1.setField2((Integer.parseInt(hatchetMerchant.getUpgradeCodeNum())+codeCount)+"");
		codeRecord1.setFromId(fromId);
		codeRecord1.setCreateTime(new Date());
		int insertCodeRecord1 = codeRecordService.insertCodeRecord(codeRecord1);
		if (insertCodeRecord1 > 0) {
			// 创建减码记录
			CodeRecord codeRecord2 = new CodeRecord();
			codeRecord2.setId(fromId);
			codeRecord2.setAgentId(agent.getID());
			codeRecord2.setName(agent.getAgentName());
			codeRecord2.setCount(codeCount);
			codeRecord2.setType("1");
			codeRecord2.setToId(toId);
			//操作前升级码数量
			codeRecord2.setField1((agent.getFastCount()+codeCount)+"");
			//操作后升级码数量
			codeRecord2.setField2(agent.getFastCount()+"");
			codeRecord2.setCreateTime(new Date());
			int insertcodeRecord2 = codeRecordService.insertCodeRecord(codeRecord2);
			if (insertcodeRecord2 > 0) {
				return true;
			} else {
				throw new RuntimeException("创建升级码减码记录失败");
			}
		} else {
			throw new RuntimeException("创建升级码加码记录失败");
		}
	}

	/**
	 * 查询经理人信息
	 * 
	 * @param hatchetMerchant
	 * @return
	 */
	public List<HatchetMerchant> selectJLR(HatchetMerchant hatchetMerchant) {
		return hatchetMerchantMapper.selectJLR(hatchetMerchant);
	}

	/**
	 * 经理人审核通过
	 * @param order
	 * @return
	 */
	@Transactional
	public Map<String, Object> checkSuccess(HatchetMerchant hatchetMerchant, String createBy) {
		Map<String, Object> map = new HashMap<>();
			// 查询用户信息
			HatchetMerchant merchant = selectHatchetMerchantById(hatchetMerchant.getID());
			merchant.setIsValid("10B");
			int updateHatchetMerchant = updateHatchetMerchant(merchant);
			if (updateHatchetMerchant < 1) {
				map.put("status", BusinessStatus.FAIL);
				map.put("msg", "审核操作失败,请稍后重新审核!");
				return map;
			}
			// 给用户开后台
			SysUser sUser = new SysUser();
			sUser.setLoginName(merchant.getMerchantNo());
			String strPWD = merchant.getIdCardNumber().substring(merchant.getIdCardNumber().length()-8, merchant.getIdCardNumber().length());
			//设置密码
			sUser.setPassword(SecurityUtils.EncoderByMd5(strPWD));
			sUser.setPhonenumber(merchant.getPHONE());
			sUser.setStatus("0");
			sUser.setDelFlag("0");
			sUser.setCreateTime(new Date());
			sUser.setUpdateTime(new Date());
			sUser.setCreateBy(createBy);
			sUser.setUserName("高级顾问："+merchant.getMerchantCnName());
			sUser.setDeptId(105L);//武汉测试部
			//添加角色
			sUser.setDeptId(105L);
			// 添加角色
			SysRole role = new SysRole();
			role.setRoleName("经理人");
			List<SysRole> roleList = sysRoleService.selectRoleList(role);
			if (StringUtils.isNotEmpty(roleList)) {
				SysRole sysRole = roleList.get(0);
				Long[] roleIds = { sysRole.getRoleId() };
				sUser.setRoleIds(roleIds);
				int insertUser = sysUserService.insertUser(sUser);
				if (insertUser < 1) {
					throw new RuntimeException("用户开后台失败 请稍后再试");
				}
				//添加一条信用卡托管记录日志
				DepositLog depositLog = new DepositLog();
				depositLog.setBrokerid(merchant.getID());
				depositLog.setStatus("10B");
				depositLog.setUid(createBy);
				depositLog.setTime(new Date());
				depositLog.setType("1");//表示日志是关于后台审核高级经理人的
				int insertDepositLog = depositLogService.insertDepositLog(depositLog);
				if (insertDepositLog<1) {
					throw new RuntimeException("委托日志创建失败,请稍后再试");
				}
				//给高级经纪人发送审核通过消息
				//(int)();
				//13927459802,高级经纪人,我的页面-高级权限页面
				//13026186535,高级经纪人,我的页面-高级权限页面
				String	params = merchant.getPHONE()+","+SMSConst.JLR_TITLE+","+"我的页面-高级权限页面";
				//创建一条短信日志记录
				OptLog optLog = new OptLog();
				optLog.setUid(merchant.getID());
				optLog.setPhone(merchant.getPHONE());
				optLog.setSend(params);
				optLog.setReturnMsg("success");
				optLog.setType("deposit_broker_apply_success_sms");
				optLog.setAcq(Constans.SYS_ACQ);
				optLog.setCreateTime(new Date());
				optLogService.insertOptLog(optLog);
				//发送短信
				String eee = ChuangLanSmsUtil.sendSMSVar(SMSConst.deposit_broker_apply_success, params);
				System.out.println(eee);
			}
		map.put("status", BusinessStatus.SUCCESS);
		map.put("msg", "操作成功!");
		return map;
	}

	/**
	 * 经理人审核不通过
	 * 
	 * @param orderId
	 * @return
	 */
	@Transactional
	public Map<String, Object> checkFail(HatchetMerchant hatchetMerchant,String createBy) {
		Map<String, Object> map = new HashMap<>();
		HatchetOrderPayment paramOrder = new HatchetOrderPayment();
		paramOrder.setMerchantId(hatchetMerchant.getID());
		paramOrder.setTradeType("SJJLR");
		paramOrder.setSTATUS("10B");
		List<HatchetOrderPayment> selectHatchetOrderPaymentList = orderPaymentService.selectHatchetOrderPaymentList(paramOrder);
		HatchetOrderPayment orderPayment =  new HatchetOrderPayment();
		if (StringUtils.isNotEmpty(selectHatchetOrderPaymentList)) {
			orderPayment = selectHatchetOrderPaymentList.get(0);
		} else {
			map.put("status", BusinessStatus.FAIL);
			map.put("msg", "订单信息没找到!");
			return map;
		}
			/*// 已退款状态
			orderPayment.setSTATUS("11TK");
			int updateHatchetOrderPayment = orderPaymentService.updateHatchetOrderPayment(orderPayment);
			if (updateHatchetOrderPayment < 1) {
				map.put("status", BusinessStatus.FAIL);
				map.put("msg", "操作失败!");
				return map;
			}*/
			// 查询用户信息
			HatchetMerchant merchant = selectHatchetMerchantById(orderPayment.getMerchantId());
			// 针对该用户创建一条分润记录
			HatchetMoneyChange moneyChange = new HatchetMoneyChange();
			moneyChange.setID(StringUtils.randomUUID());
			moneyChange.setTrxAmt(orderPayment.getTrxAmt());
			moneyChange.setMoneyType("10TK");
			moneyChange.setUserId(merchant.getMerchantNo());
			moneyChange.setPaymentOrderId(orderPayment.getOrderNo());
			moneyChange.setSTATUS("10B");
			moneyChange.setComplateTime(new Date());
			moneyChange.setCreateTime(new Date());
			int insert = moneyChangeService.insertHatchetMoneyChange(moneyChange);
			if (insert > 0) {
				// 审核失败
				merchant.setIsValid("10C");
				// 修改用户的totalMoney
				BigDecimal oldMoney = merchant.getTotalMoney();
				if (StringUtils.isNull(oldMoney)) {
					oldMoney = new BigDecimal("0");
				}
				BigDecimal newMoney = oldMoney.add(orderPayment.getTrxAmt());
				merchant.setTotalMoney(newMoney);
				int update = updateHatchetMerchant(merchant);
				if (update < 1) {
					throw new RuntimeException("操作失败");
				}
				//添加一条信用卡托管记录日志
				DepositLog depositLog = new DepositLog();
				depositLog.setBrokerid(merchant.getID());
				depositLog.setStatus("10C");
				depositLog.setUid(createBy);
				depositLog.setTime(new Date());
				//借用ykRate 字段显示拒绝原因
				depositLog.setRemark(hatchetMerchant.getYkRate());
				depositLog.setType("1");
				int insertDepositLog = depositLogService.insertDepositLog(depositLog);
				if (insertDepositLog<1) {
					throw new RuntimeException("操作失败");
				}
				//给申请用户发送审核未通过短信
				//13927459802,高级经纪人,您注册时间不满一周
				String	params = merchant.getPHONE()+","+SMSConst.JLR_TITLE+",:"+hatchetMerchant.getYkRate();
				//创建一条短信日志记录
				OptLog optLog = new OptLog();
				optLog.setUid(merchant.getID());
				optLog.setPhone(merchant.getPHONE());
				optLog.setSend(params);
				optLog.setReturnMsg("success");
				optLog.setType("deposit_broker_apply_defeated_sms");
				optLog.setAcq(Constans.SYS_ACQ);
				optLog.setCreateTime(new Date());
				optLogService.insertOptLog(optLog);
				//发送短信
				String eee = ChuangLanSmsUtil.sendSMSVar(SMSConst.deposit_broker_apply_defeated, params);
				System.out.println(eee);
			} else {
				throw new RuntimeException("操作失败");
			}
		map.put("status", BusinessStatus.SUCCESS);
		map.put("msg", "操作成功!");
		return map;
	}

	/**
	 * 高级经纪人查询托管卡用户列表
	 * @param hatchetMerchant
	 * @return
	 */
	public List<HatchetMerchant> selectHatchetMerchantForJLR(HatchetMerchant hatchetMerchant) {
		return hatchetMerchantMapper.selectHatchetMerchantForJLR(hatchetMerchant);
	}
	
	/**
	 * 递归查询用户
	 * @param merchantList 用户列表
	 * @param parentPhone 当前用户手机号
	 * @return
	 */
	public List<HatchetMerchant> getMerchantTree(List<HatchetMerchant> merchantList ,String parentPhone) {   
		HatchetMerchant merchant = new HatchetMerchant();    
		merchant.setParentPhone(parentPhone);
		List<HatchetMerchant> list = hatchetMerchantMapper.selectHatchetMerchantList(merchant);        
		if (StringUtils.isNotEmpty(list)) {
			for (HatchetMerchant hatchetMerchant : list) {
				merchantList.add(hatchetMerchant);
				getMerchantTree(merchantList,hatchetMerchant.getPHONE());
			}
		}
		return merchantList;
		}
	
	/**
	 * 查询用户的上级推荐用户 （只在同一个代理商下面）
	 * @param merchantList 用户列表
	 * @param parentPhone 当前用户手机号
	 * @return
	 */
	@Override
	public List<HatchetMerchant> getMerchantParentTree(String phone) {   
		//获取当前用户信息
		List<HatchetMerchant> merchantList = new ArrayList<>();
		HatchetMerchant merchant = selectHatchetMerchantByPhone(phone);
		merchantList.add(merchant);
		String agentId = merchant.getAgentId();
		boolean isGoOn = true;
		while (isGoOn) {
			if (StringUtils.isNotNull(merchant)) {
				merchant =  selectHatchetMerchantByPhone(merchant.getParentPhone());
				//查到当前用户和上级推荐人不是同一个代理商的就不再向上查
				if (StringUtils.isNotNull(merchant)) {
					if (!agentId.equals(merchant.getAgentId())) {
						isGoOn =false;
					}else {
						merchantList.add(merchant);
					}
				}else {
					return merchantList;
				}
				
			} else {
				return merchantList;
			}
			
		}
		return merchantList;
	}

	/**
	 * h5用户注册
	 */
	@Override
	public Map<String, Object> h5Register(HatchetMerchant merchant) {
		 Map<String, Object> map = new HashMap<>();
		// 添加
		SysUser sUser = new SysUser();
		sUser.setLoginName(merchant.getPHONE());
		String strPWD = merchant.getPASSWD();
		//设置密码
		sUser.setPassword(SecurityUtils.EncoderByMd5(strPWD));
		sUser.setPhonenumber(merchant.getPHONE());
		sUser.setStatus("0");
		sUser.setDelFlag("0");
		sUser.setCreateTime(new Date());
		sUser.setUpdateTime(new Date());
		sUser.setCreateBy(merchant.getPHONE());
		sUser.setUserName(merchant.getPHONE());
		sUser.setDeptId(108L);//长沙市场部
		// 添加角色
		SysRole role = new SysRole();
		role.setRoleName("H5用户");
		List<SysRole> roleList = sysRoleService.selectRoleList(role);
		if (StringUtils.isNotEmpty(roleList)) {
			SysRole sysRole = roleList.get(0);
			Long[] roleIds = { sysRole.getRoleId() };
			sUser.setRoleIds(roleIds);
			int insertUser = sysUserService.insertUser(sUser);
			if (insertUser < 1) {
				throw new RuntimeException("用户注册失败 请稍后再试");
			} else {
				//添加到merchant表
			//调用徐建接口
				
			}
		}
		return map;
	}

	@Override
	public List<HatchetMerchant> selectAllMerchant() {
		return hatchetMerchantMapper.selectAllMerchant();
	}

	
}

